package com.example.controller;



import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.DeleteRequest;
import com.example.common.ErrorCode;
import com.example.common.Result;
import com.example.exception.BusinessException;
import com.example.model.dto.*;
import com.example.model.po.Team;
import com.example.model.po.User;
import com.example.model.po.UserTeam;
import com.example.model.vo.TeamUserVO;
import com.example.service.ITeamService;
import com.example.service.IUserService;

import com.example.service.IUserTeamService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;


import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 队伍 前端控制器
 * </p>
 *
 * @author LinHui
 * @since 2024-04-19
 */
@RestController
@RequestMapping("/team")
@CrossOrigin(origins = "http://localhost:5173/", allowCredentials = "true")
@Api("队伍管理")
public class TeamController {

    @Resource
    private ITeamService teamService;

    @Resource
    private IUserService userService;

    @Resource
    private IUserTeamService userTeamService;



    @ApiOperation("添加队伍信息")
    @PostMapping("/add")
    public Result<Long> addTeam(@RequestBody TeamAddDTO team, HttpServletRequest request) {
        //team 判空
        if (team == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        User loginUser = userService.getLoginUser(request);
        //保存
        //boolean flag = teamService.save(team);
        Team tagTeam = new Team();
        BeanUtils.copyProperties(team, tagTeam);
        long teamId = teamService.addTeam(tagTeam, loginUser);
        //if (!flag) {
        //    throw new BusinessException(ErrorCode.SYSTEM_ERROR, "插入失败");
        //}


        //返回
        return Result.success(teamId);

    }



    @ApiOperation("删除队伍信息")
    @PostMapping("/delete")
    public Result<Boolean> deleTeam( Long id) {
        //id 判空，且不能小于零
        if (id == null || id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        //根据id删除
        boolean flag = teamService.removeById(id);
        //判断是否删除失败
        if (!flag) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "删除失败");
        }

        //返回是否删除成功

        return Result.success(flag);

    }



    @ApiOperation("更改队伍信息")
    @PostMapping("/update")
    public Result<Boolean> updateTeam(@RequestBody TeamUpdateRequestDTO teamUpdateRequestDTO, HttpServletRequest request) {
        //team 判空
        if (teamUpdateRequestDTO == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        //根据id更改数据
        //boolean flag = teamService.updateById(team);
        boolean flag = teamService.updateTeam(teamUpdateRequestDTO, userService.getLoginUser(request));
        //确定是否更改成功，更改失败，抛出异常
        if (!flag) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "更新失败");
        }


        //返回更改成功数据
        return Result.success(flag);
    }



    @ApiOperation("获取队伍信息")
    @GetMapping ("/get")
    public Result<Team> getTeam( Long id) {
        //team 判空
        if (id == null || id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        //根据id更改数据
        Team team = teamService.getById(id);


        //确定是否更改成功，更改失败，抛出异常
        if (team == null) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "为查询到该队伍");
        }


        //返回更改成功数据
        return Result.success(team);
    }



    @ApiOperation("获取所有队伍信息")
    @GetMapping ("/list")
    public Result<List<TeamUserVO>> listTeams( TeamQuery teamQuery, HttpServletRequest request) {
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean isAdmin = userService.isAdmin(request);
        // 1、查询队伍列表
        List<TeamUserVO> teamList = teamService.listTeams(teamQuery, isAdmin);


        final List<Long> teamIdList = teamList.stream().map(TeamUserVO::getId).collect(Collectors.toList());
        // 2、判断当前用户是否已加入队伍
        QueryWrapper<UserTeam> userTeamQueryWrapper = new QueryWrapper<>();
        try {
            User loginUser = userService.getLoginUser(request);
            userTeamQueryWrapper.eq("userId", loginUser.getId());
            userTeamQueryWrapper.in("teamId", teamIdList);
            List<UserTeam> userTeamList = userTeamService.list(userTeamQueryWrapper);
            // 已加入的队伍 id 集合
            Set<Long> hasJoinTeamIdSet = userTeamList.stream().map(UserTeam::getTeamId).collect(Collectors.toSet());
            teamList.forEach(team -> {
                boolean hasJoin = hasJoinTeamIdSet.contains(team.getId());
                team.setHasJoin(hasJoin);
            });
        } catch (Exception e) {
        }
        // 3、查询已加入队伍的人数
        QueryWrapper<UserTeam> userTeamJoinQueryWrapper = new QueryWrapper<>();
        userTeamJoinQueryWrapper.in("teamId", teamIdList);
        List<UserTeam> userTeamList = userTeamService.list(userTeamJoinQueryWrapper);
        // 队伍 id => 加入这个队伍的用户列表
        Map<Long, List<UserTeam>> teamIdUserTeamList = userTeamList.stream().collect(Collectors.groupingBy(UserTeam::getTeamId));
        teamList.forEach(team -> team.setHasJoinNum(teamIdUserTeamList.getOrDefault(team.getId(), new ArrayList<>()).size()));
        return Result.success(teamList);

    }


    @ApiOperation("分页查询")
    @GetMapping ("/list/page")
    public Result<List<Team>> listTeamAsPage( TeamQuery teamQuery) {
        //判空
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //

        Team team = new Team();
        BeanUtils.copyProperties(teamQuery, team);
        //teamService.lambdaQuery()
        //        .setEntity(team)
        //        .list();
        QueryWrapper<Team> qw = new QueryWrapper<>(team);
        List<Team> teams = teamService
                .page(new Page<Team>(teamQuery.getPageNum(), teamQuery.getPageSize()), qw)
                .getRecords();

        return Result.success(teams);

    }


    @ApiOperation("用户加入队伍")
    @PostMapping("/join")
    public Result<Boolean> joinTeam(@RequestBody TeamJoinRequestDTO teamJoinRequestDTO, HttpServletRequest request) {
        //判空
        if (teamJoinRequestDTO == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        User loginUser = userService.getLoginUser(request);
        boolean result = teamService.joinTeam(teamJoinRequestDTO, loginUser);


        return Result.success(result);

    }




    @ApiOperation("用户退出队伍")
    @PostMapping("/quit")
    public Result<Boolean> quitTeam(@RequestBody TeamQuitRequestDTO teamQuitRequestDTO, HttpServletRequest request) {
        //判空
        if (teamQuitRequestDTO == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        User loginUser = userService.getLoginUser(request);
        boolean result = teamService.quitTeam(teamQuitRequestDTO, loginUser);


        return Result.success(result);

    }


    @PostMapping("/delete")
    public Result<Boolean> deleteTeam(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = deleteRequest.getId();
        User loginUser = userService.getLoginUser(request);
        boolean result = teamService.deleteTeam(id, loginUser);
        if (!result) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "删除失败");
        }
        return Result.success(true);
    }


    /**
     * 获取我创建的队伍
     *
     * @param teamQuery
     * @param request
     * @return
     */
    @ApiModelProperty("查询自己创建的团队")
    @GetMapping("/list/my/create")
    public Result<List<TeamUserVO>> listMyCreateTeams(TeamQuery teamQuery, HttpServletRequest request) {
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        teamQuery.setUserId(loginUser.getId());
        List<TeamUserVO> teamList = teamService.listTeams(teamQuery, true);
        return Result.success(teamList);
    }


    /**
     * 获取我加入的队伍
     *
     * @param teamQuery
     * @param request
     * @return
     */
    @ApiOperation("查询自己加入的团队")
    @GetMapping("/list/my/join")
    public Result<List<TeamUserVO>> listMyJoinTeams(TeamQuery teamQuery, HttpServletRequest request) {
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        QueryWrapper<UserTeam> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", loginUser.getId());
        List<UserTeam> userTeamList = userTeamService.list(queryWrapper);
        // 取出不重复的队伍 id
        // teamId userId
        // 1, 2
        // 1, 3
        // 2, 3
        // result
        // 1 => 2, 3
        // 2 => 3
        Map<Long, List<UserTeam>> listMap = userTeamList.stream()
                .collect(Collectors.groupingBy(UserTeam::getTeamId));

        List<Long> idList = new ArrayList<>(listMap.keySet());
        teamQuery.setIdList(idList);
        List<TeamUserVO> teamList = teamService.listTeams(teamQuery, true);
        return Result.success(teamList);
    }




}
